<template>
  <div>
    <ConditionCard
      shadow="never"
      body-style="padding: 24px 24px 6px 24px;"
      @search="onSearch"
      @reset="onReset"
    >
      <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="80px">
        <el-row>
          <!-- 年级-->
          <el-col :span="8">
            <el-form-item :label="$t('preparatoryGraduation.common.grade')">
              <el-date-picker
                v-model="queryForm.grade"
                value-format="yyyy"
                align="right"
                type="year"
                @change="handleGradeChange"
                :placeholder="$t('common.pla.pleaseSelect')"
                clearable
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <!-- 学院 -->
          <el-col :span="8">
            <el-form-item :label="$t('preparatoryGraduation.common.college')">
              <DictSelect v-model="queryForm.college" :data="source.colleges" @change="handleCollegeChange"/>
            </el-form-item>
          </el-col>
          <!-- 专业 -->
          <el-col :span="8">
            <el-form-item :label="$t('preparatoryGraduation.common.major')">
              <DictSelect v-model="queryForm.major" :data="source.majors"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- 结业年份 -->
          <el-col :span="8">
            <el-form-item label="结业年份">
              <el-date-picker
                v-model="queryForm.completionYear"
                value-format="yyyy"
                align="right"
                type="year"
                :placeholder="$t('common.pla.pleaseSelect')"
                clearable
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <!-- 结业状态 -->
          <el-col :span="8">
            <el-form-item label="结业状态">
              <DictSelect v-model="queryForm.status" :data="source.status"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ConditionCard>
    <el-card shadow="never" body-style="padding: 24px;">
      <div class="edu-page-title mg-bottom leftPadding">
        <span>预科结业资格审核列表</span>
      </div>
      <div class="float-left mg-bottom">
        <el-input
          v-model.trim="queryForm.searchText"
          placeholder="请输入学生姓名或学号"
          prefix-icon="el-icon-search"
          @change="onSearch"
        />
      </div>
      <div class="float-right mg-bottom">
        <el-button  @click="handlePublish(1)">{{$t('message.publish')}}</el-button>
        <el-button  @click="handlePublish(0)">取消发布</el-button>
        <el-button type="danger" @click="handleBatch(1)">批量取消结业</el-button>
        <el-button type="primary" @click="handleBatch(2)">批量结业</el-button>
      </div>
      <el-table
        :data="tableData"
        :order="false"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="50">
        </el-table-column>
        <el-table-column
          label="学号"
          prop="studentId"
          show-overflow-tooltip
          min-width="90"
          align="center"
        />
        <el-table-column
          label="姓名"
          prop="studentName"
          show-overflow-tooltip
          min-width="110"
          align="center"
        />
        <el-table-column
          label="学院"
          prop="collegeI18n"
          show-overflow-tooltip
          min-width="110"
          align="center"
        />
        <el-table-column
          label="专业"
          prop="majorI18n"
          show-overflow-tooltip
          min-width="110"
          align="center"
        />
        <el-table-column
          label="年级"
          prop="grade"
          show-overflow-tooltip
          min-width="110"
          align="center"
        />
        <el-table-column
          label="入学时间"
          prop="enrollmentDate"
          show-overflow-tooltip
          min-width="110"
          align="center"
          :formatter="(row, column, cellValue) => timeFormate(cellValue)"
        />
        <el-table-column
          label="结业年份"
          prop="completionYear"
          show-overflow-tooltip
          min-width="110"
          align="center"
        />
        <el-table-column
          label="机审详情"
          show-overflow-tooltip
          min-width="110"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="showDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
          <el-table-column
            label="结业证明材料"
            show-overflow-tooltip
            min-width="110"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="!scope.row.file">无</div>
              <div v-else>
                <el-button type="text" @click="downloadFile(scope.row.file, scope.row.fileName)">{{scope.row.fileName}}</el-button>
              </div>
            </template>
          </el-table-column>
        <el-table-column
          label="延期状态"
          show-overflow-tooltip
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isDelay === isDelay.yes" type="danger" size="mini">已延期</el-tag>
            <el-tag v-else type="success" size="mini">未延期</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="结业状态"
          show-overflow-tooltip
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === status.unCompletion" type="danger" size="mini">未结业</el-tag>
            <el-tag v-else-if="scope.row.status === status.completion" type="success" size="mini">已结业</el-tag>
            <el-tag v-else type="warning" size="mini">退回生源地</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="发布状态"
          show-overflow-tooltip
          min-width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.publish == 1" type="success" size="mini">已发布</el-tag>
            <el-tag v-else  size="mini">未发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="结业"
          show-overflow-tooltip
          min-width="110"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.copyStatus"
              :active-value="status.completion"
              :inactive-value="status.unCompletion"
              @change="graduate(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          show-overflow-tooltip
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
           
              <!-- 未结业，且未延期时显示 -->
              <el-button type="text" v-if="scope.row.status==status.unCompletion&&scope.row.isDelay === isDelay.no"  @click="delay(scope.row)">延期</el-button>
              <!-- 退回生源 -->
              <el-button type="text" v-if="scope.row.status==status.unCompletion&&scope.row.isDelay === isDelay.yes && scope.row.status !== status.backToPlace" @click="backToPlace(scope.row)">退回生源地</el-button>
              
              <!--已结业或者延期时显示-->
              <el-upload
                v-if="scope.row.status==status.completion || scope.row.isDelay==isDelay.yes"
                :headers="{'X-Token': $store.state.session.sessionid}"
                :data="{bucketname: 'face', folderpath: 'file'}"
                :on-success="handleSuccess"
                :before-upload="handleBeforeUpload"
                class="upload-demo"
                :file-list="fileList"
                action="/api/commonservice/obsfile/uploadfile"
              >
                <el-button type="text" @click="currentRow = scope.row" >上传</el-button>
              </el-upload> 
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="page.pageNum_"
        :page-sizes="[20, 50, 100, 500, 1000]"
        :page-size="page.pageSize_"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="float: right;margin:10px 60px 0 0;"
        :small="false"
        @keyup.enter.native="handleKey"
        @size-change="onPageSizeChange"
        @current-change="onCurrentPageChange"
        @keyup.enter.native.self.stop="
            e => {
              onCurrentPageChange(e.target.value);
            }
          "
      />
    </el-card>
  </div>
</template>
<script>
  import request from 'common/src/api/preparatoryGraduation/completionAudit';
  import completionAudit from '../completionAudit.js';
  export default {
    name: "completionAudit",
    mixins: [completionAudit],
    data() {
      return {
        defaultQueryForm: {
          grade: (new Date().getFullYear() - 1).toString(),
          college: '',
          major: '',
          completionYear: '',
          status: '',
          searchText: ''
        },
        status: {
          unCompletion: '1', // 未结业
          completion: '2', // 已结业
          backToPlace: '3' // 退回生源地
        },
        isDelay: {
          yes: '1', // 已延期
          no: '0' // 未延期
        },
        queryForm: {},
        currentRow: {},
        fileList: [],
        maxFileSize: 10 * 1024 * 1024,
        multipleSelection:[]
      };
    },
    created() {
      this.queryForm = { ...this.defaultQueryForm };
      const condition = this.$route.query.condition;
      if (Object.keys(condition || {}).length) {
        this.queryForm = Object.assign(this.queryForm, condition);
        this.page = Object.assign(this.page, condition);
      }
    },
    mounted() {
      this.loadTableData();
    },
    methods: {
      onSearch() {
        this.loadTableData();
      },
      onReset() {
        this.$refs['queryForm'].resetFields();
        this.queryForm = Object.assign({}, this.defaultQueryForm);
        this.page = Object.assign({}, this.defaultPage);
        this.loadTableData();
      },
      // 加载表格数据
      loadTableData() {
        this.triggingLoading();
        request.pageList({ ...this.queryForm, ...this.page }).then(res => {
          const data = res.data;
          data.list.forEach(item => {
            item.status = (item.status || 1).toString();
            item.isDelay = (item.isDelay || 0).toString();
            item.copyStatus = item.status;
          });
          this.tableData = data.list;
          this.page = {
            total: data.total_,
            pageNum_: data.pageNum_,
            pageSize_: data.pageSize_
          };
          this.triggingLoading();
        });
      },
      showDetail(row) {
        const cloneTableData = _.cloneDeep(this.tableData);
        const index = cloneTableData.findIndex(item => item.studentId === row.studentId)
        this.$router.push({
          path: '/auditDetail',
          query: {
            studentId: row.studentId,
            index: index,
            currentPath: this.$route.path,
            tableData: cloneTableData,
            condition: { ...this.queryForm, ...this.page }
          }
        })
      },
      // 结业
      graduate(row) {
        // 取消结业状态无需提示
        if (row.status === this.status.completion) {
          this.doGraduate(row);
          return;
        }
        request.getCreditsInfo(row).then(res => {
          const data = res && res.data;
          if (!data || !data.length) {
            this.$message({
              type: 'error',
              message: '该学生无对应的结业审核标准，无法进行结业操作'
            });
            row.copyStatus = this.status.unCompletion;
            return;
          }
          // 学分达标时，直接改变结业状态
          if (this.creditsIsUpToStandard(data)) {
            // 已退回生源地
            if (row.status.toString() === this.status.backToPlace) {
              this.graduateConfirm(row, "学生已退回生源地，是否确认结业");
              return;
            }
            this.doGraduate(row);
            return;
          }
          const tip = row.status.toString() === this.status.backToPlace
            ? "学生已退回生源地且学分未达标，是否确认结业"
            : "学生学分不达标，是否确认结业";
          this.graduateConfirm(row, tip);
        });
      },
      creditsIsUpToStandard(data) {
        const parentLabIDs = [];
        data.forEach(item => {
          if (item.parentLabID) {
            parentLabIDs.push(item.parentLabID);
          }
        });
        return !data.filter(item => !parentLabIDs.includes(item.labID))
        .some(item => item.credit > (item.getCredit || 0));
      },
      graduateConfirm(row, tip) {
        this.$eduConfirm(
          tip,
          "结业"
        ).then(() => {
          this.doGraduate(row);
        }).catch(() => {
          row.copyStatus = this.status.unCompletion;
        });
      },
      doGraduate(row) {
        row.status = row.copyStatus;
        this.deleteFileInfo(row);
        request.graduation(row).then(() => {
          this.loadTableData();
          this.$message({
            type: 'success',
            message: '操作成功'
          });
        });
      },
      // 延期
      delay(row) {
        this.$eduConfirm(
          "是否确定延期",
          "延期"
        ).then(() => {
          this.deleteFileInfo(row);
          this.triggingLoading();
          request.delay(row).then(() => {
            this.triggingLoading();
            this.loadTableData();
          });
        });
      },
      // 退回生源地
      backToPlace(row) {
        this.$eduConfirm(
          "是否确定退回生源地",
          "退回生源地"
        ).then(() => {
          this.deleteFileInfo(row);
          request.backToPlace(row).then(() => {
            this.triggingLoading();
            this.loadTableData();
          });
        });
      },
      handleBeforeUpload(file) {
        if (file.name.substr(file.name.lastIndexOf(".") + 1) === 'exe') {
          this.$message({
            type: 'error',
            message: '不允许上传exe文件'
          });
          return false;
        }
        if (file.size > this.maxFileSize) {
          this.$message({
            type: 'error',
            message: '上传文件大小超过10M'
          });
          return false;
        }
      },
      handleSuccess(response, file) {
        if (response.code === 200) {
          this.fileList = [];
          const data = response.data[file.name];
          this.currentRow.file = data.objectkey;
          this.currentRow.fileName = data.fileName;
          this.uploadDelayFile();
        }
      },
      // 上传
      uploadDelayFile() {
        this.triggingLoading();
        request.uploadDelayFile(this.currentRow).then(() => {
          this.$message({
            type: 'success',
            message: "操作成功"
          });
          this.loadTableData();
          this.triggingLoading();
        });
      },
      deleteFileInfo(row) {
       delete row['file'];
        delete row['fileName'];
      },
      handleKey(e) {
        if (e.target.validity.badInput) {
          this.$message({
            type: 'error',
            message: '请输入正确的页数'
          })
          return
        }
        e.target.blur()
        this.onCurrentPageChange(e.target.value)
      },
      onPageSizeChange(size) {
        // 当前页展示列表数量(pageSize)发生变化时默认将请求的页数设置为1
        this.page.pageNum_ = 1;
        this.page.pageSize_ = size;
        this.loadTableData();
      },
      onCurrentPageChange(currentPage) {
        this.page.pageNum_ = currentPage;
        this.loadTableData();
      },
      handleSelectionChange(val){
        this.multipleSelection=val;
      },
      handleBatch(status){
        if(this.multipleSelection.length == 0){
          this.$message({   
              type:"error",
              message: '至少选择一项'
          });
          return;
        }
        //批量取消结业，直接更新
        if(status==1){
          this.batchUpdate(status);
          return;
        }
        //批量结业，需要获取学生的学分是否达标
        let requests=[];
        this.multipleSelection.forEach(row=>{
          requests.push(request.getCreditsInfo(row).then(res => {
              if(res.code==200){
                return {student:row,data:res.data};
              }else{
                return {student:row,data:null};
              }
          }).catch(e=>{
              return {student:row,data:null};
          }));
        })
        Promise.all(requests).then(data=>{ 
          //无对应结业审核标准的学生   
          let invalidStudents=data.filter(row=>row.data==null||row.data.length==0);
          if(invalidStudents.length>0){
            let students=invalidStudents.map(row=>`${row.student.studentName}(${row.student.studentId})`)
            this.$message({
              type: 'error',
              message: `学生${students.join(',')}无对应的结业审核标准，无法进行结业操作`
            });
            return;
          }
          //学分不达标的学生
          invalidStudents=data.filter(row=>{
            const parentLabIDs = [];
            row.data.forEach(item => {
              if (item.parentLabID) {
                parentLabIDs.push(item.parentLabID);
              }
            });
            return row.data.filter(item => !parentLabIDs.includes(item.labID))
            .some(item => item.credit > (item.getCredit || 0));
          }); 
          if(invalidStudents.length>0){
            let students=invalidStudents.map(row=>`${row.student.studentName}(${row.student.studentId})`)
            this.$eduConfirm(              
              `<div>学生${students.join(',')}</div><span style='color:red'>学分不达标，是否确认结业</span>`,
              "结业",
              {dangerouslyUseHTMLString: true}
            ).then(() => {
              this.batchUpdate(status);
            })
          }else{
            this.batchUpdate(status);
          }
        })
      },
      batchUpdate(status){
          let param=this.multipleSelection.map(row=>{
          return {
            status:status,
            studentId:row.studentId,
            grade:row.grade,
            id:row.id
          }
        })
        request.batchUpdateComplete(param).then(res=>{
          if(res.code==200){
            this.$message({   
              type:"success",
              message: this.$t('course.operateSuccess')
            });
            this.onSearch();
          }
        });   
      },
      handlePublish(val){
        if(this.multipleSelection.length == 0){
          this.$message({   
              type:"error",
              message: '至少选择一项'
          });
          return;
        }
        let param={
          studentId:this.multipleSelection.map(row=>row.studentId),
          publish:val
        }
        request.publish(param).then(res=>{
          if(res.code==200){
            this.$message({   
              type:"success",
              message: this.$t('course.operateSuccess')
            });
            this.onSearch();
          }
        })
      }
    }
  };
</script>
<style lang="scss" scoped>
  .mg-bottom{
    margin-bottom: 15px;
  }
  .edu-page-title {
    span {
      line-height: 24px;
      display: inline-block;
      padding-right: 10px;
      font-size: 18px;
      font-weight: bold;
      color: #2b3b4e;
    }
  }
</style>
